package com.yunhe.openapi.interceptors;

import com.yunhe.openapi.util.SignDecodeUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class ApiInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if(!signValid(request)){ //sign校验
            return false;
        }
        return true;
    }

    //sign校验
    private boolean signValid(HttpServletRequest request) {
        String accessKey =  request.getParameter("accessKey");
        String sign =  request.getParameter("sign");
        String secretKey = getByAccessKey(accessKey);

        Enumeration<String> names = request.getParameterNames();
        Map<String, String> paramMap = new HashMap<>();
        while (names.hasMoreElements()){
            String key = names.nextElement();
            paramMap.put(key, request.getParameter(key));
        }
        return SignDecodeUtil.decode(paramMap, secretKey, sign);
    }

    private String getByAccessKey(String accessKey) {
        return "";
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
    }
}
